﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZhimeiSoft.Framework.Client.Utils;
using System.Configuration;

namespace ZhimeiSoft.Framework.Server.Console
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            if (!Validate())
                return;

            string serverName = this.txtServerName.Text.Trim();
            string userName = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text.Trim();
            string dbName = this.cbeDBName.SelectedValue.ToString();

            string connect_string = string.Empty;
            if (rbDBAuth.Checked)
            {
                //Windows继承身份验证
                connect_string = MainForm_Constants.Connection_String_Windows_Auth_Format;
                connect_string = string.Format(connect_string, serverName, dbName);
            }
            else if (rbUserAuth.Checked)
            {
                connect_string = MainForm_Constants.Connection_String_User_Auth_Format;
                connect_string = string.Format(connect_string, serverName, dbName, userName, password);
            }
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connect_string);
                conn.Open();

                MsgBox.MsgInfo(MainForm_Constants.Msg_Database_Connect_Success);
            }
            catch (Exception ex)
            {
                MsgBox.MsgErr(ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }

        /// <summary>
        /// 检验数据库连接，不包含数据库名的校验
        /// </summary>
        /// <returns>true:表示通过校验，false:未通过校验</returns>
        private bool ValidateWithoutDBName()
        {
            if (this.txtServerName.Text.Trim() == string.Empty)
            {
                MsgBox.MsgInfo(MainForm_Constants.Msg_DbServerName_Is_Not_Allow_Empty);
                this.txtServerName.Focus();
                return false;
            }

            if (rbUserAuth.Checked)
            {
                if (this.txtUserName.Text.Trim() == string.Empty)
                {
                    MsgBox.MsgInfo(MainForm_Constants.Msg_UserNameName_Is_Not_Allow_Empty);
                    this.txtUserName.Focus();
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 校验数据库连接
        /// </summary>
        /// <returns></returns>
        private bool Validate()
        {
            if (!ValidateWithoutDBName())
            {
                return false;
            }

            if (this.cbeDBName.SelectedIndex == 0)
            {
                MsgBox.MsgInfo(MainForm_Constants.Msg_DatabaseName_Is_Not_Allow_Empty);
                this.cbeDBName.Focus();
                return false;
            }
            
            return true;
        }

        private void rbDBAuth_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbDBAuth.Checked)
            {
                this.lblUserName.Enabled = false;
                this.lblPassword.Enabled = false;
                this.txtUserName.Enabled = false;
                this.txtPassword.Enabled = false;
            }
            else
            {
                this.lblPassword.Enabled = true;
                this.lblUserName.Enabled = true;

                this.txtPassword.Enabled = true;
                this.txtUserName.Enabled = true;
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            this.rbUserAuth.Checked = true;
            this.rbDBAuth.Checked = false;

            string conn_str = ConfigurationManager.ConnectionStrings["CharmManagerDB"].ConnectionString;
            if (!string.IsNullOrEmpty(conn_str))
            {
                string serverName = string.Empty;
                string dbName = string.Empty;
                string userName = string.Empty;
                string password = string.Empty;

                ParseConnectionString(conn_str, out serverName, out dbName, out userName, out password);
                this.txtServerName.Text = serverName;
                this.txtUserName.Text = userName;
                this.txtPassword.Text = password;
                this.cbeDBName.SelectedText = dbName;
            }

        }

        private void ParseConnectionString(string conn_str, 
            out string serverName, out string dbName, out string userName, out string password)
        {
            //Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
            //Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
            serverName = string.Empty;
            dbName = string.Empty;
            userName = string.Empty;
            password = string.Empty;

            if (string.IsNullOrEmpty(conn_str))
                return;

            if (conn_str.ToUpper().IndexOf("INTEGRATED SECURITY=SSPI") >= 0)
            {
                
            }
            else
            {

            }

        }


        public IList<string> GetDatabaseList(string conn_str)
        {
            List<string> list = new List<string>();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(conn_str);
                conn.Open();

                SqlDataAdapter da = new SqlDataAdapter(MainForm_Constants.SQL_Get_Database_List, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);

                List<string> systemDatabase = new List<string>();
                systemDatabase.Add("master");
                systemDatabase.Add("tempdb");
                systemDatabase.Add("model");
                systemDatabase.Add("msdb");

                foreach(DataRow dr in dt.Rows)
                {
                    string name = dr["Name"].ToString();
                    if (!list.Contains(name) && !systemDatabase.Contains(name))
                        list.Add(name);
                }
            }
            catch (Exception ex)
            {
                MsgBox.MsgInfo(ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

             return list;
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            // 1. 检查是否能成功连接数据库
            if (!Validate())
            {
                return;
            }
            // 2. 将数据库连接信息保存到配置文件中
            string serverName = this.txtServerName.Text.Trim();
            string dbName = this.cbeDBName.Text.Trim();
            string userName = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text.Trim();

            string connectionString = string.Empty;
            if (this.rbDBAuth.Checked)
            {
                connectionString = MainForm_Constants.Connection_String_Windows_Auth_Format;
                connectionString = string.Format(connectionString, serverName, dbName);
            }
            else
            {
                connectionString = MainForm_Constants.Connection_String_User_Auth_Format;
                connectionString = string.Format(connectionString, serverName, dbName, userName, password);
            }

        }

        private void cbeDBName_Enter(object sender, EventArgs e)
        {
            bool bFlag = ValidateWithoutDBName();
            string conn_str = string.Empty;

            string serverName = this.txtServerName.Text.Trim();
            string userName = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text.Trim();

            if (rbDBAuth.Checked)
            {
                conn_str = string.Format("Data Source={0};Integrated Security=SSPI;", serverName);
            }
            else
            {
                conn_str = string.Format("Data Source={0};User Id={1};Password={2};", serverName, userName, password);
            }

            IList<string> dbNames = GetDatabaseList(conn_str);
            foreach (string str in dbNames)
            {
                this.cbeDBName.Items.Add(str);
            }
        }
    }
}
